/**
 * 
 */
package net.corba.imp;

import logic.Document;
import logic.Template;
import net.corba.List;
import net.corba.ListHelper;
import net.corba.Logon;
import net.corba.LogonHelper;
import net.corba.Reporter;
import net.corba.ReporterHelper;
import net.corba.Retriever;
import net.corba.RetrieverHelper;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import server.GlobalConfig;
import server.ServerRetriever;

/**
 * 
 * 
 * @author renat
 */
public class CorbaServer {
	static ORB orb;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			// create and initialize the ORB
			String args2[] = { "-ORBInitialPort", "1050", "-ORBInitialHost", "localhost" };
			orb = ORB.init(args2, null);
			// get reference to rootpoa & activate the POAManager
			POA rootpoa = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));
			rootpoa.the_POAManager().activate();

			// create servant and register it with the ORB
			CorbaRetriever corbaTemplateRetriever = new CorbaRetriever(new ServerRetriever<Template>(
					GlobalConfig.TEMPLATE));
			CorbaRetriever corbaDocumentRetriever = new CorbaRetriever(new ServerRetriever<Document>(
					GlobalConfig.DOCUMENT));

			Retriever hrefTemplate = RetrieverHelper.narrow(rootpoa.servant_to_reference(corbaTemplateRetriever));
			Retriever hrefDocument = RetrieverHelper.narrow(rootpoa.servant_to_reference(corbaDocumentRetriever));
			Logon logHref = LogonHelper.narrow(rootpoa.servant_to_reference(new CorbaLogon()));
			List lustHref = ListHelper.narrow(rootpoa.servant_to_reference(new net.corba.imp.List()));
			Reporter rep = ReporterHelper.narrow(rootpoa.servant_to_reference(new net.corba.imp.Reporter()));

			// get the root naming context
			org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
			// Use NamingContextExt which is part of the Interoperable
			// Naming Service (INS) specification.
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

			ncRef.rebind(ncRef.to_name( GlobalConfig.TEMPLATE_RETRIEVER), hrefTemplate);
			ncRef.rebind(ncRef.to_name(GlobalConfig.DOCUMENT_RETRIEVER), hrefDocument);
			ncRef.rebind(ncRef.to_name("List"), lustHref);
			ncRef.rebind(ncRef.to_name("Reporter"), rep);
			ncRef.rebind(ncRef.to_name("Logon"), logHref);

			System.out.println("HelloServer ready and waiting ...");

			// wait for invocations from clients
			orb.run();
		}

		catch (Exception e) {
			System.err.println("ERROR: " + e);
			e.printStackTrace(System.out);
		}

		System.out.println("HelloServer Exiting ...");

	}

}
